package com.leyou.gateway.filters;

import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter {

    private final JwtUtils jwtUtils;
    private final StringRedisTemplate redisTemplate;

    public LoginFilter(JwtUtils jwtUtils, StringRedisTemplate redisTemplate) {
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //根据cookie名称cookie
        HttpCookie cookie = exchange.getRequest().getCookies().toSingleValueMap().get("LY_TOKEN");


        if (null == cookie) {
            //cookie为空则直接放行
            return chain.filter(exchange);
        }

        String token = cookie.getValue();


        try {
            Payload payload = jwtUtils.parseJwt(token);

            String username = payload.getUserDetail().getUsername();

            String key = RedisConstants.JTI_KEY_PREFIX + username;

            this.redisTemplate.expire(key, RedisConstants.TOKEN_EXPIRE_SECONDS, TimeUnit.SECONDS);
            return chain.filter(exchange);
        } catch (Exception e) {
            return chain.filter(exchange);
        }


    }
}